package com.message.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.message.VO.SampleInfoDTO;
import com.message.VO.SampleInfoInsterDto;
import com.message.VO.SampleInfoUpdateVo;
import com.message.VO.SampleInfoVO;
import com.message.pojo.*;
import com.message.service.SampleService;
import com.message.util.ExcelRead;
import com.message.util.ToExcel;
import com.message.util.UpLoad;
import com.mysql.fabric.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.naming.Name;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName : SampleinfoController  //类名
 * @Description :   //描述
 * @Author : yangqi  //作者
 * @Date: 2021-02-26 10:51  //创建时间
 * @modifier: //修改人
 * @modificationTime: //修改时间
 */
@Controller
public class SampleinfoController {
    @Autowired
    private SampleService sampleService;

    @RequestMapping("/findAll")
    @ResponseBody
    public PageInfo<SampleInfoVO> findAll(@RequestParam(value = "pageNum",defaultValue = "1",required = false) Integer pageNum,
                                          @RequestParam(value = "pageSize",defaultValue = "5") Integer pageSize,
                                          SampleInfoDTO sampleInfoDTO,String wuranluv,String year,String month,String day){
        if(!wuranluv.equals("")&&!wuranluv.equals(null)){
            String[] split = wuranluv.split("-");
            sampleInfoDTO.setMinPollutionRate(Float.parseFloat(split[0]));
            sampleInfoDTO.setMaxPollutionRate(Float.parseFloat(split[1]));
        }
        if (year != null && !year.equals("0")) {
            String time=year;
            if (month != null && !month.equals("0")) {
                if(month.length()==1) time+="-0"+month;
                else  time+="-"+month;
            }
            if (day != null && !day.equals("0")) {
                if(day.length()==1) time+="-0"+day;
                else time+="-"+day;
            }
            sampleInfoDTO.setTime(time);
            }
        PageInfo<SampleInfoVO> list = sampleService.findAll(sampleInfoDTO,pageNum, pageSize);
        return list;
    }
    @RequestMapping("/findToxinInfo")
    @ResponseBody
    public List<SampleToxinInfo> findToxinInfo(){
        return sampleService.findAllToxinInfo();
    }
    @RequestMapping("/findCropSpecies")
    @ResponseBody
    public List<CropSpecies> findCropSpecies(){
        return sampleService.findAllCropSpecies();
    }

    /**
     * 查询所有省份
     * @return
     */
    @RequestMapping("/findProvince")
    @ResponseBody
    public List<AddressProvince> findProvince(){
        return sampleService.findAllProvice();
    }

    /**
     * 根据省份code查询市
     * @param code 省编码
     * @return
     */
    @RequestMapping("/findCityByProvince")
    @ResponseBody
    public List<AddressCity> findCityByProvince(@RequestParam("code") String code){
        return sampleService.findCityByProvice(code);
    }

    /**
     * 根据市编码查询县
     * @param code 市编码
     * @return
     */
    @RequestMapping("/findCountyByCity")
    @ResponseBody
    public List<AddressTown> findCountyByCity(@RequestParam("code") String code){
        return sampleService.findCountyByCity(code);
    }

    /**
     * 导出
     * @param response
     * @param idList 选中的id
     */
    @RequestMapping("/exportAll")
    @ResponseBody
    public void exportAll(HttpServletResponse response,@RequestParam(value = "idList",required = false,defaultValue = "") Integer[] idList){
        List<SampleInfoVO> list=new ArrayList<>();
        if(idList.length>0){
            list = sampleService.findByIdList(idList);
        }else{
            list = sampleService.findAll();
        }
            List<List<String>> lists=new ArrayList<>();
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (int i=0;i<list.size();i++){
            SampleInfoVO sampleInfoVO = list.get(i);
            List<String> list1=new ArrayList<>();
            list1.add(sampleInfoVO.getSampleId());
            list1.add(sampleInfoVO.getProvince());
            list1.add(sampleInfoVO.getCity());
            list1.add(sampleInfoVO.getCounty());
            list1.add(sampleInfoVO.getCropCategory());
            list1.add(format.format(sampleInfoVO.getInputTime()));
            list1.add(format.format(sampleInfoVO.getSamplingTime()));
            list1.add(sampleInfoVO.getPollutionRate().toString());
            list1.add(sampleInfoVO.getToxinType());
            lists.add(list1);
        }
        String[] heads={"样品编号","省","市","县","农产品加工类型","取样时间","录入时间","真菌污染率","主要毒素"};
        String filename="ss";
        new  ToExcel<SampleInfoVO>().excel(filename,heads,response,lists);
    }

    /**
     * 导入
     * @param multipartFile 文件对象
     * @return
     * @throws ParseException
     */
    @RequestMapping("/upLoad")
    @ResponseBody
    public String upLoad(@RequestParam("file")MultipartFile multipartFile) throws ParseException {
        List<List<String>> lists = ExcelRead.readExcel(multipartFile);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        int success=0;
        int success1=0;
        for(int i=1;i<lists.size();i++){
            List<String> list = lists.get(i);
            SampleInfo sampleInfo=new SampleInfo();
            sampleInfo.setSampleId(list.get(0));
            List<AddressProvince> allProvice = sampleService.findAllProvice();
            String province="";
            for (int b=0;b<allProvice.size();b++){
                if(allProvice.get(b).getName().equals(list.get(1))){
                    province=allProvice.get(b).getCode();
                    sampleInfo.setProvince(province);
                }
            }
            List<AddressCity> cityByProvice = sampleService.findCityByProvice(province);
            String city="";
            for (int b=0;b<cityByProvice.size();b++){
                if(cityByProvice.get(b).getName().equals(list.get(2))){
                    city=cityByProvice.get(b).getCode();
                    sampleInfo.setCity(city);
                }
            }
            List<AddressTown> countyByCity = sampleService.findCountyByCity(city);
            for (int b=0;b<countyByCity.size();b++){
                if(countyByCity.get(b).getName().equals(list.get(3))){
                    sampleInfo.setCounty(countyByCity.get(b).getCode());
                }
            }
            CropCategory cropCategory = sampleService.findCropCategory(list.get(4));
            sampleInfo.setCropCategoryId(cropCategory.getId());
            sampleInfo.setInputTime(sdf.parse(list.get(5)));
            sampleInfo.setSamplingTime(sdf.parse(list.get(6)));
            sampleInfo.setPollutionRate(Float.parseFloat(list.get(7)));
             sampleService.addSampleInfo(sampleInfo);
            success++;
            String[] split = list.get(8).split(",");
            SampleToxin[] sampleToxins=new SampleToxin[split.length];
            int s=0;
            List<SampleToxinInfo> allToxinInfo = sampleService.findAllToxinInfo();
                for (int c=0;c<split.length;c++){
                    for (int b=0;b<allToxinInfo.size();b++){
                        SampleToxinInfo sampleToxinInfo = allToxinInfo.get(b);
                    if(sampleToxinInfo.getToxinType().equals(split[c])){
                        SampleToxin sampleToxin=new SampleToxin();
                        sampleToxin.setSampleInfoId(sampleInfo.getId());
                        sampleToxin.setToxinCount(Float.parseFloat(list.get(7)));
                        sampleToxin.setToxinId(sampleToxinInfo.getId());
                        sampleToxins[s]=sampleToxin;
                        s++;
                        break;
                    }
                }
            }
            success1+= sampleService.addSampleToxins(sampleToxins);
        }
        return JSON.toJSONString(String.format("主表数据添加成功%d条,从表数据添加成功%d条",success,success1));
    }

    @RequestMapping("/delete")
    @ResponseBody
    public String delete(@RequestParam("idList[]") Integer[] idList){
        int aa=sampleService.deleteByIdList(idList);
        return JSON.toJSONString(String.format("删除成功%d条",aa));
    }
    @RequestMapping("/findAllCropCategory")
    @ResponseBody
    public List<CropCategory> findAllCropCategory(){
        return sampleService.findAllCropCategory();
    }
    @RequestMapping("/insert")
    @ResponseBody
    public String insert(SampleInfo sampleInfo,@RequestParam("toxinId") Integer[] listtoxinId,
                         @RequestParam("toxinCount") Float[] listtoxinCount,@RequestParam("originalNum") String[] listoriginalNum,
                         @RequestParam("wordAddr") MultipartFile[] wordAddr,@RequestParam("txtAddr") MultipartFile[] txtAddr,
                         @RequestParam("pictureAddr") MultipartFile[] pictureAddr){
        int result = sampleService.addSampleInfo(sampleInfo);
        SampleToxin[] toxinList=new SampleToxin[listtoxinId.length];
        for(int i=0;i<listtoxinId.length;i++){
            SampleToxin sampleToxin=new SampleToxin();
            sampleToxin.setSampleInfoId(sampleInfo.getId());
            sampleToxin.setToxinId(listtoxinId[i]);
            sampleToxin.setToxinCount(listtoxinCount[i]);
            toxinList[i]=sampleToxin;
        }
        int toxins = sampleService.addSampleToxins(toxinList);
        BacterialStrainInfo[] bacterialStrainInfos=new BacterialStrainInfo[listoriginalNum.length];
        for (int i=0;i<listoriginalNum.length;i++){
            BacterialStrainInfo bacterialStrainInfo=new BacterialStrainInfo();
            bacterialStrainInfo.setSampleInfoId(sampleInfo.getId());
            bacterialStrainInfo.setSampleNum(sampleInfo.getSampleId());
            bacterialStrainInfo.setOriginalNum(listoriginalNum[i]);
            bacterialStrainInfo.setWordAddr(UpLoad.upload(wordAddr[i]));
            bacterialStrainInfo.setTxtAddr(UpLoad.upload(txtAddr[i]));
            bacterialStrainInfo.setPictureAddr(UpLoad.upload(pictureAddr[i]));
            bacterialStrainInfos[i]=bacterialStrainInfo;
        }
        int resultb = sampleService.addBacterialStrainInfo(bacterialStrainInfos);
        return JSON.toJSONString(String.format("主表数据添加成功%d条,从表数据添加成功%d条",result,(toxins+resultb)));
    }
    @RequestMapping("/findOne")
    @ResponseBody
    public SampleInfoUpdateVo findOne(@RequestParam("id")Integer id){
        SampleInfoUpdateVo byId = sampleService.findById(id);
        byId.setListBacterial(sampleService.selectBacterialStrainInfo(id));
        return byId;
    }
    @RequestMapping("/update")
    @ResponseBody
    public String updateSampleInfo(@RequestParam(value = "JsonPojo")String JsonPojo,
                                   @RequestParam(value = "fileList",required = false) MultipartFile[] fileList){
        String result="修改失败";
        SampleInfoInsterDto sampleInfoInsterDto= JSONObject.parseObject(JsonPojo, SampleInfoInsterDto.class);
        SampleInfo sampleInfo=sampleInfoInsterDto.getSampleInfo();
        int resuA=sampleService.updateSampleInfo(sampleInfo);
        sampleService.deleteToxinByPrimaryKey(sampleInfo.getId());
        //添加主表id到sampletoxin集合
        for (int i = 0; i < sampleInfoInsterDto.getListToxin().length; i++) {
            sampleInfoInsterDto.getListToxin()[i].setSampleInfoId(sampleInfo.getId());
        }
        int resuB=0;
        //批量新增
        if(sampleInfoInsterDto.getListToxin().length>0){
            resuB=sampleService.addSampleToxins(sampleInfoInsterDto.getListToxin());
        }
        List<BacterialStrainInfo> bacterialStrainInfos=sampleService.selectBacterialStrainInfo(sampleInfo.getId());
        List<BacterialStrainInfo> beHave=new ArrayList<>();
        for (int i = 0; i < bacterialStrainInfos.size(); i++) {
            boolean have=false;
            for (int i1 = 0; i1 < sampleInfoInsterDto.getListBacterial().length; i1++) {
                if(bacterialStrainInfos.get(i).getId()==sampleInfoInsterDto.getListBacterial()[i1].getId()){
                    have=true;
                    break;
                }
            }
            if(have){
                beHave.add(bacterialStrainInfos.get(i));
            }else {
                new File(bacterialStrainInfos.get(i).getWordAddr()).delete();
                new File(bacterialStrainInfos.get(i).getTxtAddr()).delete();
                new File(bacterialStrainInfos.get(i).getPictureAddr()).delete();
            }
        }
        List<BacterialStrainInfo> bacterialStrainInfoInsert=new ArrayList<>();
        int fileId=0;
        for (int i = 0; i < sampleInfoInsterDto.getListBacterial().length; i++) {
            boolean have=false;
            for (int y = 0; y < beHave.size(); y++) {
                if(sampleInfoInsterDto.getListBacterial()[i].getId()==beHave.get(y).getId()){
                    BacterialStrainInfo bacterialStrainInfo=new BacterialStrainInfo();
                    bacterialStrainInfo.setSampleInfoId(sampleInfo.getId());
                    bacterialStrainInfo.setSampleNum(sampleInfoInsterDto.getListBacterial()[i].getSampleNum());
                    bacterialStrainInfo.setOriginalNum(sampleInfoInsterDto.getListBacterial()[i].getOriginalNum());
                    if(sampleInfoInsterDto.getListBacterial()[i].getWordAddr().equals("1")){
                        new File(beHave.get(y).getWordAddr()).delete();
                        bacterialStrainInfo.setWordAddr(UpLoad.upload(fileList[fileId++]));
                    }else {
                        bacterialStrainInfo.setWordAddr(beHave.get(y).getWordAddr());
                    }
                    if(sampleInfoInsterDto.getListBacterial()[i].getTxtAddr().equals("1")){
                        new File(beHave.get(y).getTxtAddr()).delete();
                        bacterialStrainInfo.setTxtAddr(UpLoad.upload(fileList[fileId++]));
                    }else {
                        bacterialStrainInfo.setTxtAddr(beHave.get(y).getTxtAddr());
                    }
                    if(sampleInfoInsterDto.getListBacterial()[i].getPictureAddr().equals("1")){
                        new File(beHave.get(y).getPictureAddr()).delete();
                        bacterialStrainInfo.setPictureAddr(UpLoad.upload(fileList[fileId++]));
                    }else {
                        bacterialStrainInfo.setPictureAddr(beHave.get(y).getPictureAddr());
                    }
                    bacterialStrainInfoInsert.add(bacterialStrainInfo);
                    have=true;
                    break;
                }
            }
            if (!have){
                sampleInfoInsterDto.getListBacterial()[i].setSampleInfoId(sampleInfo.getId());
                sampleInfoInsterDto.getListBacterial()[i].setWordAddr(UpLoad.upload(fileList[(fileId+0)]));
                sampleInfoInsterDto.getListBacterial()[i].setTxtAddr(UpLoad.upload(fileList[(fileId+1)]));
                sampleInfoInsterDto.getListBacterial()[i].setPictureAddr(UpLoad.upload(fileList[(fileId+2)]));
                bacterialStrainInfoInsert.add(sampleInfoInsterDto.getListBacterial()[i]);
            }
        }

        int resuC=0;
        //删除数据所有的BacterialStrain
        sampleService.deleteBacterialStrainInfoByPrimaryKey(sampleInfo.getId());
        if(sampleInfoInsterDto.getListBacterial().length>0){
            resuC=sampleService.insertBacterialStrainInfoByList(bacterialStrainInfoInsert.toArray(new BacterialStrainInfo[bacterialStrainInfoInsert.size()]));
        }

        if(resuA>0){
            result="修改成功";
            if(sampleInfoInsterDto.getListToxin().length>0){
                result +=String.format(";从数据数据毒素信息一共%d条,成功%d条,失败%d条",sampleInfoInsterDto.getListToxin().length, resuB ,sampleInfoInsterDto.getListToxin().length-resuB);
            }
            if(sampleInfoInsterDto.getListBacterial().length>0){
                result +=String.format(";从数据菌株信息一共%d条,成功%d条,失败%d条",bacterialStrainInfoInsert.size(), resuC ,bacterialStrainInfoInsert.size()-resuC);
            }
        }
        return JSON.toJSONString(result);
    }
}
